package com.kde.crisisdepalabras;

import java.io.Serializable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.facebook.Session;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements TaskComplete, Serializable 
{
	private GlobalClass globalVariable;
	
	//private TextView userName;
	public SessionState state;
	public static Session session;
	//public static String uid;
	
	private UiLifecycleHelper uiHelper;
	
    private ImageView mainAnimation;
	private AnimationDrawable animation;
	
	private boolean userMainActivityReady;
	private boolean facebookButtonReady = false;
	private boolean facebookConnected = false;
	private boolean timerFinished = false;
	private LoginButton authButton;
	private GraphUser userFacebook;
	private TextView loadingText;
	private Animation anim;
	   
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
  		setContentView(R.layout.activity_main);

  		this.userMainActivityReady = false;
  		this.mainAnimation = (ImageView)findViewById(R.id.presentation);
    	this.mainAnimation.setBackgroundResource(R.drawable.presentation);
    	this.animation = (AnimationDrawable)mainAnimation.getBackground();   
    	this.animation.start();
    	
    	this.loadingText = (TextView)findViewById(R.id.txtLoading);
    	this.globalVariable = (GlobalClass)getApplicationContext();

    	anim = new AlphaAnimation(0.0f, 1.0f);
    	anim.setDuration(100); 
    	anim.setStartOffset(20);
    	anim.setRepeatMode(Animation.REVERSE);
    	anim.setRepeatCount(Animation.INFINITE);
    	loadingText.startAnimation(anim);
    	
    	new CountDownTimer(6000, 1000) 
    	{
    	     public void onTick(long millisUntilFinished)
    	     {
    	        // mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
    	     }

    	     public void onFinish() 
    	     {
    	    	 timerFinished = true;
    	    	 StartGame();
    	     }
    	}.start();
    	
    	
	    this.authButton = (LoginButton)findViewById(R.id.authButton);
	    this.authButton.setLoginBehavior(SessionLoginBehavior.SUPPRESS_SSO);
	    
	    
	    
	   // this.userName = (TextView)findViewById(R.id.user_name);
	    
	   
	    this.authButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback()
	    {
            public void onUserInfoFetched(GraphUser user) 
            {
            	userFacebook = user;
            	Log.d("","Enter User Info Change CallBack.");
            	session = Session.getActiveSession();
            	facebookButtonReady = true;
            	
            	if(session != null && session.isOpened() && user != null) 
            	{
            		globalVariable.setId(user.getId());
            		globalVariable.setName(user.getFirstName());
            		globalVariable.setSurname(user.getLastName());
            		
            		facebookConnected = true;
            		StartGame();
                } 
            	else
            	{
            		facebookConnected = false;
            	}
            	
            	
            } 
        }); 

	    
	    uiHelper = new UiLifecycleHelper(this, callback);
	    uiHelper.onCreate(savedInstanceState);
	    /*
	    ServiceTask service = new ServiceTask();
		service.setTaskComplete(this);
		service.execute("http://appeventscomar.fatcow.com/wsPreguntas/user3.php");
		*/	    
	}
	
	private void StartGame()
	{
		if (this.facebookConnected == true && this.timerFinished == true && this.facebookButtonReady == true && this.userMainActivityReady == false )
		{
			this.userMainActivityReady = true;
			this.anim.cancel();
			Intent userMainActivity = new Intent(MainActivity.this, UserMainActivity.class);
			//userMainActivity.putExtra("USER_NAME", this.userFacebook.getName());
			startActivityForResult(userMainActivity,0); 
			
			//userMainActivity.UserFacebook = this.userFacebook;
		}
		
		if (this.facebookConnected == false && this.timerFinished == true && facebookButtonReady == true)
		{
			this.anim.cancel(); 
			this.authButton.setVisibility(View.VISIBLE);
		}
	}
	
	
	@Override
	public void onResume()
	{
	    super.onResume();
	    
	    Session session = Session.getActiveSession();
	    if (session != null && (session.isOpened() || session.isClosed()) ) 
	    {
	        onSessionStateChange(session, session.getState(), null);
	    }
	    
	    uiHelper.onResume();
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
	    super.onActivityResult(requestCode, resultCode, data);
	    uiHelper.onActivityResult(requestCode, resultCode, data);
	    
	    if(resultCode == 0) 
	    {
	        finish();
	    }
	}
	

	@Override
	public void onPause()
	{
	    super.onPause();
	    uiHelper.onPause();
	}
	
	@Override
	public void onDestroy()
	{
	    super.onDestroy();
	    uiHelper.onDestroy();
	}

	@Override
	public void onSaveInstanceState(Bundle outState)
	{
	    super.onSaveInstanceState(outState);
	    uiHelper.onSaveInstanceState(outState);
	}
	
	private static final String TAG = "MainFragment";
	
	private void onSessionStateChange(Session session, SessionState state, Exception exception)
	{
		this.state = state;
	    if (state.isOpened())
	    {
	        Log.i(TAG, "Logged in...");
	    } 
	    else if (state.isClosed()) 
	    {
	        Log.i(TAG, "Logged out...");
	    }
	}

	private Session.StatusCallback callback = new Session.StatusCallback()
	{
	    @Override
	    public void call(Session session, SessionState state, Exception exception) 
	    {
	        onSessionStateChange(session, state, exception);
	    }
	};
	 
	@Override
	public void onComplete(JSONArray result) 
	{
		String IP = "";
		try {
			
			for(int i=0;i<result.length();i++)
			{
				JSONObject json_data = result.getJSONObject(i);
				IP = json_data.getString("FirstName");
				Toast.makeText(this, IP, Toast.LENGTH_SHORT).show();
			}
			
		} 
		catch (JSONException ex)
		{
			Log.e(getClass().getName(), ex.getMessage());
		}		
	}
	
	
}
